package com.si.anddos;

import java.util.ArrayList;

import com.si.anddos.dpadapters.AnddosDbAdapter;
import com.si.anddos.search.SearchMaker;
import com.si.anddos.search.SearchResult;
import com.si.anddos.search.SearchResultAdapter;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.database.Cursor;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;

/**
 * A class representing searching for file via filestube
 * 
 * @author Carlos Martinez
 * 
 */

public class SearchActivity extends OptionsMenuActivity {
	
	private AnddosDbAdapter mDbHelper;
	
	private SearchMaker searchMaker = new SearchMaker();
	private ProgressDialog progressDialog;

	private SearchResultAdapter searchAdapter;
	
	private ListView listSearchResults;
	private EditText editTextSearch;

	private Button buttonOptions;
	
	private String Nresult="";
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mDbHelper = new AnddosDbAdapter(this);
		setContentView(R.layout.search);
		setTitle(R.string.titleSearch);		
		
		editTextSearch = (EditText) findViewById(R.id.editTextSearch);
//		registerForContextMenu(editTextSearch);
		
		//Add item to the contextmenu of the EditText "editTextSearch"
		editTextSearch.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){

			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				 menu.add(0, v.getId(), 0, "Historial");
			}
		});
		
		//Soft keyboard search
		editTextSearch.setOnEditorActionListener(new OnEditorActionListener(){
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                 if(arg1 == EditorInfo.IME_ACTION_SEARCH) 
                 {
                	 performSearch();
                 }
                 return false;
            }
         });
		
		//Control if the item selected is from provider rapidshare.com
		listSearchResults = (ListView) findViewById(R.id.listSearchResults);
		listSearchResults.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            	
            	if(searchAdapter.getItem(position).getAddress().contains("rapidshare.com")){
            		Intent i = new Intent(SearchActivity.this, DownloadNewActivity.class);
            		i.putExtra("url", searchAdapter.getItem(position).getAddress());
            		startActivity(i);
            	}
            	else{
            		Toast.makeText(parent.getContext(), "The only provider allowed to download is RAPIDSHARE.COM", Toast.LENGTH_SHORT).show();
            	}
            }
          });
		
		
		//Copy the url to clipboard (long click)
		listSearchResults.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int pos, long id) {
				//Copy to clipboard the address
				ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); 
				clipboard.setText(searchAdapter.getItem(pos).getAddress().toString());
				Toast.makeText(parent.getContext(), "The URL is copied to the clipboard", Toast.LENGTH_SHORT).show();

				// TODO Auto-generated method stub
				return false;
			}
		});
		
		//Button Options
		// button to new options click listener
		buttonOptions = (Button) findViewById(R.id.buttonShowOptions);
		buttonOptions.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				callOptions();
			}
		});
		
	
	}
	
	

	@Override
	public void onWindowFocusChanged(boolean hasFocus){
	    if(hasFocus){
	    	if(this.getIntent().getExtras() != null){
	    		int identifier=this.getIntent().getExtras().getInt("identifier");
	    		mDbHelper.open();
	    		Cursor cur=mDbHelper.getHistorialElement(identifier);
	    		editTextSearch.setText(cur.getString(cur.getColumnIndex(AnddosDbAdapter.colHistorialName)));
	    		
//	    		if(cur.getString(cur.getColumnIndex(AnddosDbAdapter.colHistorialExtension))==Globals.AllExtensions){
//	    			Globals.extension="";
//	    			Globals.POS_EXTENSION=0;
//	    		}
//	    		else{
//	    			Globals.extension=cur.getString(cur.getColumnIndex(AnddosDbAdapter.colHistorialExtension));
//	    			if(Globals.extension=="rar")
//	    				Globals.POS_EXTENSION=1;
//	    			else if(Globals.extension=="wmv")
//	    				Globals.POS_EXTENSION=2;
//	    			else if(Globals.extension=="avi")
//	    				Globals.POS_EXTENSION=3;
//	    			else if(Globals.extension=="mpg")
//	    				Globals.POS_EXTENSION=4;
//	    			else if(Globals.extension=="mpeg")
//	    				Globals.POS_EXTENSION=5;
//	    			else if(Globals.extension=="mp3")
//	    				Globals.POS_EXTENSION=6;
//	    			else if(Globals.extension=="wma")
//	    				Globals.POS_EXTENSION=7;
//	    			else if(Globals.extension=="zip")
//	    				Globals.POS_EXTENSION=8;
//	    			
//	    		}
//	    		
//	    		Globals.MAX_SEARCHS=Integer.parseInt(cur.getString(cur.getColumnIndex(AnddosDbAdapter.colHistorialNumberSearchs)));
//	    		
//	    		
	    		this.getIntent().removeExtra("identifier");
	    	}
	    }
	}	
	public void UpdateDbVar(){
		//Update values of id and number of elements of the historial
		mDbHelper.open();
		Globals.numberHistorialElements=mDbHelper.getNumberHistorialElements();
		Globals.HistorialIdMin=mDbHelper.getOlderHistorialElement();
		Globals.HistorialIdMax=mDbHelper.getNewerHistorialElement();
		mDbHelper.close();
	}


	 public boolean onContextItemSelected(MenuItem item) {  
	        if(item.getTitle()=="Historial"){showHistorial(item.getItemId());}   
	        else {return false;}  
	    return true;  
	 }  
	 
	 private void showHistorial(int id){
		 Intent i = new Intent(this, HistorialListActivity.class);
		 startActivity(i);
	 }
	
	public void makeSearch(View v) {
    	performSearch();
	}
	
	
	private void callOptions(){
		Intent i = new Intent(this, ShowOptionsActivity.class);
		startActivity(i);
	}

	private void saveHistorial(){
		String name = editTextSearch.getText().toString();
		long id;
		boolean ok=false;
		String extension="";
		String rapidshare,hotfile,megaupload,megashares,fileserve,filesonic;
		rapidshare=hotfile=megaupload=megashares=fileserve=filesonic="";
		
		
		if(Globals.rapidshare)
			rapidshare="rapidshare";
		if(Globals.megashares)
			megashares="megashares";
		if(Globals.megaupload)
			megaupload="megaupload";
		if(Globals.hotfile)
			hotfile="hotfile";
		if(Globals.fileserve)
			fileserve="fileserve";
		if(Globals.filesonic)
			filesonic="filesonic";
		
		
		if(Globals.extension=="")
			extension=Globals.AllExtensions;
		else
			extension=Globals.extension;
		
		
		mDbHelper.open();
        // save account to database
        // add check if acounts info exists on rapidshare!!
		if(Globals.numberHistorialElements==20){
			ok=mDbHelper.updateHistorialElement(Globals.HistorialIdMin, name, 
					Globals.HistorialIdMax+1,extension,Integer.toString(Globals.MAX_SEARCHS)
					,Nresult,rapidshare,megaupload,filesonic,fileserve,megashares,hotfile);
			if(ok==false)
				Log.v("Historial Table Update", "Error updating the table");
			else{
				Globals.HistorialIdMax++;
			}
		}
		else if(Globals.numberHistorialElements<20){
			id = mDbHelper.createHistorialElement(Globals.HistorialIdMax+1, name,extension,
					Integer.toString(Globals.MAX_SEARCHS),Nresult,rapidshare
					,megaupload,filesonic,fileserve,megashares,hotfile);
        	if (id < 0) {
        		// add fail to store into database
        	}
        	else{
        		Globals.HistorialIdMax++;
        		Globals.numberHistorialElements++;
        	}
		}
       
        
        mDbHelper.close();
		
	}
	
	
	private void performSearch() {
		String phrase = editTextSearch.getText().toString();
		
		if(TextUtils.isEmpty(phrase))
    	{
    		createAlertNoPhrase();
    	}
    	else
    	{
    		
    		UpdateDbVar();
    		progressDialog = ProgressDialog.show(SearchActivity.this,
    				"Please wait...", "Retrieving data...", true, true);

    		PerformSearchTask task = new PerformSearchTask();
    		task.execute(phrase);
    		progressDialog
    				.setOnCancelListener(new CancelTaskOnCancelListener(task));
    	}
	}
	
		
	private void createAlertNoPhrase() {
    	// create alert dialog if user left empty account field
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle(R.string.alertSearchTitle)
    			.setMessage(R.string.alertSearchMessage)
    			.setCancelable(false)
    			.setNegativeButton(R.string.alertSearchNegButton, new DialogInterface.OnClickListener() {
    				public void onClick(DialogInterface dialog, int id) {
    					dialog.cancel();
    				}
    			});
    	AlertDialog alert = builder.create();
    	alert.show();
		
	}

	private class PerformSearchTask extends
			AsyncTask<String, Void, ArrayList<SearchResult>> {

		@Override
		protected ArrayList<SearchResult> doInBackground(String... params) {
			String phrase = params[0];
			return searchMaker.makeSearch(phrase);
		}

		@Override
		protected void onPostExecute(final ArrayList<SearchResult> result) {
			runOnUiThread(new Runnable() {
				public void run() {
					
					Nresult=Integer.toString(result.size());
					
					if(result.isEmpty())
						Toast.makeText(SearchActivity.this, R.string.textSearchNoResults, Toast.LENGTH_SHORT).show();
					
					searchAdapter = new SearchResultAdapter(SearchActivity.this, R.layout.search_row, result);
					listSearchResults.setAdapter(searchAdapter);
					
					
					saveHistorial();
					//listSearchResults.setBackgroundColor(Color.BLUE);
					
					if (progressDialog != null) {
						progressDialog.dismiss();
						progressDialog = null;
					}
				}
			});
			
		}

	}

	private class CancelTaskOnCancelListener implements OnCancelListener {
		private AsyncTask<?, ?, ?> task;

		public CancelTaskOnCancelListener(AsyncTask<?, ?, ?> task) {
			this.task = task;
		}

		public void onCancel(DialogInterface dialog) {
			if (task != null) {
				task.cancel(true);
			}
		}
	}
	
}